import { useHistory } from 'react-router';
import React, { useContext } from 'react';
import { useEffect, useState } from 'react';
import { Button, Modal } from '@arco-design/web-react';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import { GlobalContext } from '@/context';

type CustomConfirmMadelProps = {
  when: boolean;
  message?: string;
};
function CustomConfirmMadel(props: CustomConfirmMadelProps) {
  const { when = false, message } = props;
  const { rtl } = useContext(GlobalContext);
  const history = useHistory();
  const t = useLocale(locale);
  const [opened, setOpened] = useState(false);
  const [unblock, setUnblock] = useState(null);
  const [newUrl, setNewUrl] = useState(null);
  const [action, setAction] = useState<any>();

  const onConfirm = () => {
    unblock?.();
    if (action === 'PUSH') {
      history.push(newUrl);
    } else if (action === 'POP') {
      history.goBack();
    } else if (action === 'REPLACE') {
      history.replace(newUrl);
    }
    setOpened(false);
  };

  useEffect(() => {
    console.log('when', when);
    if (!when) {
      unblock?.();
      return;
    }
    if (unblock) {
      return;
    }
    const cancel = history.block((location, action) => {
      if (when) {
        setOpened(true);
      }
      setNewUrl(location);
      setAction(action);
      return false;
    });

    setUnblock(() => {
      return cancel;
    });
  }, [when, unblock]);

  useEffect(() => {
    return () => {
      unblock?.();
    };
  }, []);

  return (
    <>
      <Modal
        className={rtl ? 'rtl' : ''}
        closable
        style={{ width: '400px' }}
        title={<>{t['modal.title']}</>}
        visible={opened}
        simple
        onCancel={() => {
          setOpened(false);
        }}
        footer={
          <>
            <Button type="primary" onClick={onConfirm}>
              {t['modal.button']}
            </Button>
          </>
        }
      >
        <div style={{ textAlign: 'center' }}>
          <div>{message || t['modal.desc']}</div>
        </div>
      </Modal>
    </>
  );
}

export default CustomConfirmMadel;
